var WXBizDataCrypt = require('./WXBizDataCrypt')
var https = require('https');
var appId = 'wx24fc90f55d6cb518'
var appSecret = 'e05535194136e1837004622ac8a72358'
var express = require('express');
var app = express();

var DBHelper = require('./DBHelper');
var dbManager = new DBHelper();

app.get('/test', function (req, res) {
	res.send("Hellow");
})

//查询新番总列表
app.get('/season_info', function (req, res) {
	dbManager.getAllSeasonInfo( result => {
		res.send(result);
	});
})

//用户登录时请求
//向微信接口拿取用户session_key
//解密算出unionId
//通过unionId去服务器查询收藏信息
app.get('/user_login', function (req, res) {
	//解密用户数据
	var reqJson = req.query;
	var code = req.query.loginCode;
	// console.log("code:"+code);
	var getSessionUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
	var req = https.get(getSessionUrl, function(response){
		var encryptedData = reqJson.encryptedData;
		var iv = reqJson.iv;
		var body = '';
		response.on('data', function(data) {
			body += data;
		});

		response.on('end', function() {
			var sessionData = JSON.parse(body);
			console.log("body:"+body);
			if (body.errcode) {
				console.log("error");
				return
			}
			// console.log("session_key:"+sessionData.session_key);
			// console.log("encryptedData:"+encryptedData);
			// console.log("iv:"+iv);
			var pc = new WXBizDataCrypt(appId, sessionData.session_key)
			var data = pc.decryptData(encryptedData , iv)
			//用户开放平台唯一ID
			// console.log(data);
			// console.log("unionIdID:"+data.unionId);
			dbManager.getUserInfo(data, result => {
				//没查到就新建一个用户
				if(result == false){
					dbManager.createUser(data);
				}
			});
			res.send(data.unionId);
		});
	});
})

//获取收藏总信息
app.get('/user_followInfo',function (req,res){
	var reqJson = req.query;
	var unionId = reqJson.unionId;

	dbManager.getUserAllFollowInfo({unionId:unionId}, result => {
		res.send(result);
	});
})

//修改收藏标记
app.get('/user_follow',function (req,res){
	var reqJson = req.query;
	var unionId = reqJson.unionId;
	var seasonId = reqJson.seasonId;
	var type = reqJson.followType;
	var obj = {
		unionId:unionId,
		seasonId:seasonId,
		followType:type
	};

	dbManager.setUserFollowInfo(obj,result =>{
		res.send({seasonId:seasonId,followType:type});
	});
})

var server = app.listen(8888, '0.0.0.0', function () {

	var host = server.address().address
	var port = server.address().port

	dbManager.connectDB();
	console.log("http://%s:%s",host,port);
})
